package cn.kgc;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.CountDownLatch;

/**
 * @author YC
 */
public class UpdateNodeData implements Watcher {

    /**
     * 倒计时闩锁，初始值为1
     */
    private static final CountDownLatch COUNT_DOWN_LATCH = new CountDownLatch(1);

    public static void main(String[] args) {
        try (ZooKeeper zooKeeper = new ZooKeeper("192.168.8.106:2181", 5000, new UpdateNodeData())) {
            // 等待连接（倒计时闩锁值为0才能连接）
            COUNT_DOWN_LATCH.await();
            // 连接状态为：CONNECTED
            System.out.println(zooKeeper.getState());
            Stat stat = zooKeeper.setData("/kgc-test", "修改的测试值".getBytes(), -1);
            if (stat != null) {
                System.out.println("修改成功");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 事件通知
     *
     * @param watchedEvent 事件
     */
    @Override
    public void process(WatchedEvent watchedEvent) {
        // 客户端监听服务端的连接事件
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            // 连接成功则释放倒计时闩锁（值-1）
            COUNT_DOWN_LATCH.countDown();
        }
    }

}
